import React, { useEffect, useState } from 'react'
import ShowDrawer from '@/components/ShowDrawer'
import {
    Form,
    Input,
    Tree,
    TreeSelect,
    message,
} from 'antd';
import { addInfo, updateInfo } from '@/api/system/dept';
import { rules } from './rules'
import { IDepartment } from '../types';

const DepartmentInfo = (props: any) => {
    const { info, list } = props;
    const expandedKeys= ['-1']
    const deptList = [
        {
            deptName: '浙江交工集团',
            deptId: '-1',
            children: [
                ...list
            ]
        }
    ]
    let fieldNames = {
        label: 'deptName',
        value: 'deptId',
        children: 'children',
    }
    //初始化表单
    let initForm = {
        deptName: '',
        deptCode:'',
        status:1,
        area:'',
        parentId:'-1',
        orderNum:'',
    }
    const [form] = Form.useForm<IDepartment>();
    const [infoForm, setInfoForm] = useState<IDepartment>({ ...initForm, ...info });

    //提交表单
    const onFinish = async () => {
        form.validateFields().then(async values => {
            let sendForm = { ...infoForm, ...values };
            if (sendForm.deptId) {
                //编辑
                await updateInfo(sendForm);
            } else {
                //新增addInfo
                await addInfo(sendForm);
            }
            message.success('操作成功');
            form.resetFields();
            props.submit();
        }).catch(info => {
            console.log('Validate Failed - ', info);
        });
    }

    return (
        <ShowDrawer
            close={() => props.close()}
            submit={() => onFinish()}>
            <Form
                form={form}
                name="info"
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
                initialValues={{ remember: false }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item label="角色名称" name="deptName" initialValue={infoForm.deptName} rules={rules.deptName}>
                    <Input placeholder="请输入角色名称" />
                </Form.Item>
                <Form.Item label="角色权限" name="parentId" initialValue={infoForm.parentId} rules={rules.parentId}>
                    <TreeSelect
                        style={{ width: '100%' }}
                        value={infoForm.deptName}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="请选择部门"
                        allowClear
                        treeExpandedKeys={expandedKeys}
                        treeData={deptList}
                        fieldNames={fieldNames} />
                </Form.Item>
            </Form>
        </ShowDrawer>
    )


}
export default DepartmentInfo
